import { ProtoIDs } from "../core/ProtoIDs";
import { Server, ServerStatus } from "../core/server";
import { NetDispatcher } from "../tools/NetDispatcher";
import { Dispatcher } from "../tools/Dispatcher";

export class NetManager {
    private static _install: NetManager;
    private _heartTimer: Laya.Timer;

    public static get instance() {
        if (this._install == null) {
            this._install = new NetManager();
        }
        return this._install;
    }
    public server: Server;
    public init() {
        this._heartTimer = new Laya.Timer();

        this.addListener();
        this.server = new Server(ProtoIDs.getMap(), {
            addr: "ws://127.0.0.1:8080",
            jsonEnabled: false,
            logger: console
        });
        this.server.connect();

    }

    private addListener() {
        this.server.on(ServerStatus.Opened, this, this.onSocketOpen);
        this.server.on(ServerStatus.Closed, this, this.onSocketClose);
        NetDispatcher.addListener(ProtoIDs.loginMsgID.S2C_Login, this, this.S2C_Login);

    }

    private onSocketOpen() {
        // this.onHeartBeat();
        this._heartTimer.loop(10000, this, this.onHeartBeat);
    }
    private onSocketClose() {
        this._heartTimer.clearAll(this);
    }
    private onHeartBeat() {
        this.server.sendHeartData(ProtoIDs.loginMsgID.HEART);
    }


    public C2S_Login(): void {

        let ms: protobuf.C2S_Login = new protobuf.C2S_Login();
        ms.account = "test1";
        ms.password = "123321";
        // ms.msg= [12];
        // // ms.msg= ;
        this.server.sendData(ProtoIDs.loginMsgID.C2S_Login, ms, protobuf.C2S_Login)
    }
    
    private S2C_Login(data: Uint8Array) {
        let s2c_login2 = protobuf.S2C_Login.decode(data)
        // this._username = s2c_login2.account;
        // console.log('S2C_Login')
        // console.log(JSON.stringify(s2c_login2))
        Dispatcher.dispatch(ProtoIDs.loginMsgID.S2C_Login, s2c_login2);
    }
}
